package com.swfgui.game
{
	import com.swfgui.managers.server.ServerManager;
	import com.swfgui.utils.TimeUtil;
	
	import flash.events.TimerEvent;
	import flash.text.TextField;
	import flash.utils.Timer;

	/**
	 * 倒计时，单位为秒
	 * @author llj
	 */
	public class CountDown
	{
		private var _endTime:int;
		/**
		 * 设置以后，自动把剩余时间更新上去
		 * @default 
		 */
		public var viewLabel:TextField;
		private var timer:Timer;
		private var leftSecond:int;
		
		public var timeFormat:String;		
		/**
		 * n天 nn:nn:nn
		 * @default 
		 */
		public static const TIME_FOTMAT2:String = "n天 nn:nn:nn";
		/**
		 * n天n时n分n秒
		 * @default 
		 */
		public static const TIME_FOTMAT1:String = "n天n时n分n秒";
		
		public function CountDown()
		{
			timer = new Timer(1000);
			timeFormat = TIME_FOTMAT2;
		}
		
		private var onComplete:Function;
		private var onCompleteArgs:Array;
		
		public function start(endTime:int = -1, onComplete:Function=null, onCompleteArgs:Array=null):void
		{
			if(endTime > 0)
			{
				this.endTime = endTime;
			}
			if(leftTime > 0)
			{
				this.onComplete = onComplete;
				this.onCompleteArgs = onCompleteArgs;
					
				timer.addEventListener(TimerEvent.TIMER, onTimer);
				timer.start();				
				leftSecond = leftTime;
				updateLabel();
			}
		}
		
		/**
		 * 每隔一秒剩余时间减少一秒
		 * @param event
		 */
		protected function onTimer(event:TimerEvent):void
		{
			if(leftSecond <= 0)
			{
				if(onComplete != null)
				{
					onComplete.apply(null, onCompleteArgs);
					onComplete = null;
					onCompleteArgs = null;
				}
				stop();
			}
			else
			{				
				leftSecond--;
			}
			
			updateLabel();
		}
		
		private function updateLabel():void		
		{
			if(viewLabel)
			{
				if(timeFormat == TIME_FOTMAT1)
				{
					viewLabel.text = TimeUtil.formatTime1(leftSecond);
				}
				else if(timeFormat == TIME_FOTMAT2)
				{
					viewLabel.text = TimeUtil.formatTime2(leftSecond);
				}
			}
		}
		
		public function stop():void
		{
			timer.removeEventListener(TimerEvent.TIMER, onTimer);
			timer.stop();
			onComplete = null;
			onCompleteArgs = null;
		}
		
		/**
		 * 剩余秒数
		 * @return 
		 */
		public function get leftTime():int
		{
			//var t:int = _endTime - ServerManager.serverTime / 1000;			
			//return t > 0 ? t : 0;
			return _endTime;
		}
		
		public function get leftTimeString():String
		{
			if(timeFormat == TIME_FOTMAT1)
			{
				return TimeUtil.formatTime1(leftTime);
			}
			else(timeFormat == TIME_FOTMAT2)
			{
				return TimeUtil.formatTime2(leftTime);
			}
		}
		
		
		/**
		 * 截止时间戳，单位秒
		 * @default 
		 */
		public function get endTime():int
		{
			return _endTime;
		}

		/**
		 * @private
		 */
		public function set endTime(value:int):void
		{
			_endTime = value;
			leftSecond =  leftTime;
		}

	}
}